<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "material".
 *
 * @property integer $id
 * @property string $name
 * @property string $attribute
 * @property integer $country_id
 * @property double $inventory
 * @property string $unit
 * @property double $price
 * @property integer $level
 * @property string $description
 * @property string $create_at
 * @property string $update_at
 *
 * @property Country $country
 * @property UserMaterial[] $userMaterials
 */
class Material extends \app\models\BaseModel {
    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'material';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['name', 'attribute', 'country_id', 'inventory', 'unit', 'price', 'level'], 'required'],
            [['country_id', 'level'], 'integer'],
            [['inventory', 'price'], 'number'],
            [['create_at', 'update_at'], 'safe'],
            [['name', 'attribute', 'unit', 'description'], 'string', 'max' => 255],
            [['country_id'], 'exist', 'skipOnError' => true, 'targetClass' => Country::className(), 'targetAttribute' => ['country_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => '原料id',
            'name' => '原料名称',
            'attribute' => '原料类别',
            'country_id' => '所属国家',
            'inventory' => '原料库存',
            'unit' => '原料单位',
            'price' => '原料价格',
            'level' => '原料等级',
            'description' => '原料描述',
            'create_at' => '创建时间',
            'update_at' => '更新时间',
        ];
    }

    public function fields() {
        $fields = [
            'id',
            'name',
            'attribute',
            'country',
            'inventory',
            'unit',
            'price',
            'level',
            'description',
        ];
        $fields = array_combine($fields, $fields);

        return $fields;
    }

    public function extraFields() {
        $fields = [
            'country_id',
            'create_at',
            'update_at',
        ];
        $fields = array_combine($fields, $fields);
        return $fields;
    }

    public function getCountry() {
        return $this->hasOne(Country::className(), ['id' => 'country_id'])->inverseOf('materials');
    }

    public function getUserMaterials() {
        return $this->hasMany(UserMaterial::className(), ['material_id' => 'id'])->inverseOf('material');
    }
}
